﻿using System;
using System.Text.RegularExpressions;

namespace SimpleForum.Utils
{
    public static class StringHelper
    {
        //remove URL unfriendly characters (basically replace them all with a -)
        public static string Slugify(this string Title, int MaxLength = 50)
        {
            string Slug = Title.ToLower();

            Slug = Regex.Replace(Slug, @"[^a-z0-9\s-]", "");
            Slug = Regex.Replace(Slug, @"[\s-]+", " ").Trim();
            Slug = Slug.Substring(0, Slug.Length <= MaxLength ? Slug.Length : MaxLength).Trim();
            Slug = Regex.Replace(Slug, @"\s", "-");

            return Slug;
        }

        // turns 3352 into 3.3K, 1514 into 1.5K, etc.
        public static string PrettyNumbers(this int Num)
        {
            if (Num >= 100000000) return PrettyNumbers(Num / 1000000) + "M";
            if (Num >= 100000) return PrettyNumbers(Num / 1000) + "K";
            if (Num >= 1000) return (Num / 1000D).ToString("0.#") + "K";

            return Num.ToString("#,0");
        }

        // returns an MD5 hash (lowercase) of the passed string
        public static string MD5Hash(this string String)
        {
            System.Security.Cryptography.MD5 MD5 = System.Security.Cryptography.MD5.Create();
            byte[] InputBytes = System.Text.Encoding.ASCII.GetBytes(String);
            byte[] Hash = MD5.ComputeHash(InputBytes);
 
            System.Text.StringBuilder SB = new System.Text.StringBuilder();
            for (int i = 0; i < Hash.Length; i++)
            {
                SB.Append(Hash[i].ToString("x2"));
            }

            return SB.ToString();
        }
    }
}